package com.sisyphus.spinach.extension;

import android.os.CountDownTimer;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

public class LifecycleCountDownTimer extends CountDownTimer implements DefaultLifecycleObserver {

    private static final long COUNT_DOWN_INTERVAL = 1000;

    private final TextView mTextView;
    private final String mText, mFormat;


    public LifecycleCountDownTimer(Lifecycle lifecycle, TextView view) {
        this(60 * 1000, lifecycle, view, null);
    }

    public LifecycleCountDownTimer(int seconds, Lifecycle lifecycle, TextView view) {
        this(seconds, lifecycle, view, null);
    }

    /**
     * @param seconds       秒
     * @param lifecycle     绑定生命周期
     * @param view          显示的View
     * @param format        显示的字符串
     */
    public LifecycleCountDownTimer(
            int seconds,
            Lifecycle lifecycle,
            TextView view,
            String format
    ) {
        super(seconds, COUNT_DOWN_INTERVAL);
        mTextView = view;
        mFormat = format;
        mText = view.getText().toString();
        lifecycle.addObserver(this);
    }


    @Override
    public void onFinish() {
        mTextView.setText(mText);
        mTextView.setEnabled(true);
    }


    @Override
    public void onTick(long millisUntilFinished) {
        mTextView.setEnabled(false);

        long args = millisUntilFinished / COUNT_DOWN_INTERVAL;

        if (mFormat == null) {
            mTextView.setText(String.valueOf(args));

        } else {
            mTextView.setText(String.format(mFormat, args));
        }
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        this.cancel();
    }

}
